/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.delivery;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiji.www.frameworks.utils.DensityUtils;

import java.math.BigDecimal;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.base.DanluBaseActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.widget.loadlayer.LoaddingLayout;
import cn.com.hd.mall.web.webservices.entity.freedom.request.coupon.CheckSeparateOrderListsReq;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.CheckSeparateOrderListsResponse;
import rx.Subscription;

import static cn.com.dhc.danlu.R.id.tv_title;
import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-09-20 11:10<br/>
 * <p>
 * <p>
 * no paging  logic
 * </p>
 */
public class OrderSplitListActivity extends DanluBaseActivity implements OnClickListener {
    private static final String PAY_STATUS_AWAIT = "00";
    private static final String PAY_STATUS_COM = "03";
    private static final String PAY_CANCELED = "07";

    private String mOrderNo;
    private Subscription mSubscription;
    private LoaddingLayout llLayer;
    private TextView mTvOrderNo;
    private LinearLayout llPayChildContainer;

    /**
     * 启动活动OrderSplitListActivity
     *
     * @param context 上下文
     * @param orderNo 订单号
     */
    public static void startSelf(Context context, String orderNo) {
        Intent intent = new Intent(context, OrderSplitListActivity.class);
        intent.putExtra("orderNo", orderNo);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_split_list);

        initView();
        fetchData();
    }

    private void fetchData() {
        mOrderNo = getIntent().getStringExtra("orderNo");
        mTvOrderNo.setText(String.format(getResources().getString(R.string.order_split_child_tips), mOrderNo));
        releaseSubscription();
        llLayer.showLoaddingView();
        agent.getApi()
                .getOrderSplitList(new CheckSeparateOrderListsReq(agent.getToken(), mOrderNo))
                .compose(OperatorUtils.<CheckSeparateOrderListsResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<CheckSeparateOrderListsResponse>() {
                    @Override
                    protected void onSuccess(CheckSeparateOrderListsResponse model) {
                        refreshUI(model);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        llLayer.showErrorView(displayMessage);
                    }
                });
    }

    @SuppressLint("SetTextI18n")
    private void refreshUI(CheckSeparateOrderListsResponse model) {
        llPayChildContainer.removeAllViews();
        List<CheckSeparateOrderListsResponse.PaymentList> list = model.getPaymentInfoList();
        if (list.isEmpty()) {
            llLayer.showEmptyView("暂无拆分支付单");
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            CheckSeparateOrderListsResponse.PaymentList payEntry = list.get(i);
            View childView = View.inflate(this, R.layout.dl_ordersplit_item, null);
            TextView tvPayNo = (TextView) childView.findViewById(R.id.tv_pay_no);
            TextView tvPayAmount = (TextView) childView.findViewById(R.id.tv_pay_amount);
            TextView tvStatus = (TextView) childView.findViewById(R.id.tv_pay_status);
            tvPayNo.setText("支付单：" + payEntry.getSeparatePaymentNo());
            BigDecimal amountBd = CommonUtils.fenToYuan(new BigDecimal(payEntry.getSeparateOrderAmount()));
            tvPayAmount.setText("支付金额：" + amountBd.toPlainString());

            switch (payEntry.getPayStatus()) {
                case PAY_STATUS_AWAIT:
                    tvStatus.setText("未支付");
                    tvStatus.setTextColor(getResources().getColor(R.color.color_f26936));
                    break;
                case PAY_STATUS_COM:
                    tvStatus.setText("已支付");
                    tvStatus.setTextColor(getResources().getColor(R.color.color_459602));
                    break;
                case PAY_CANCELED:
                    tvStatus.setText("已取消");
                    tvStatus.setTextColor(getResources().getColor(R.color.color_f26936));
                    break;
                default:
                    tvStatus.setVisibility(View.GONE);
                    break;
            }

            llPayChildContainer.addView(childView);
            if (i != list.size() - 1) {
                llPayChildContainer.addView(creatDivider());
            }
        }
        llLayer.showContentView();
    }

    private View creatDivider() {
        View view = new View(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(this, 1));
        view.setBackgroundColor(getResources().getColor(R.color.color_d5d5d5));
        view.setLayoutParams(lp);
        return view;
    }

    @Override
    protected void onDestroy() {
        releaseSubscription();
        super.onDestroy();
    }

    private void releaseSubscription() {
        if (null != mSubscription) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_error_retry || v.getId() == R.id.btn_reload) {
            fetchData();
        } else {
            finish();
        }
    }

    private void initView() {
        llLayer = (LoaddingLayout) findViewById(R.id.ll_loading);
        mTvOrderNo = (TextView) findViewById(R.id.tv_order_no);
        TextView mTvPayTips = (TextView) findViewById(R.id.tv_pay_tips);
        TextView tvTitle = (TextView) findViewById(tv_title);
        CommonUtils.dividerShowTextStyle(mTvPayTips, getResources().getString(R.string.pay_tips), 0, 1, 14, 14, R.color.color_fb6236);
        llPayChildContainer = (LinearLayout) findViewById(R.id.ll_payorder_container);
        tvTitle.setText(R.string.order_split);
        findViewById(R.id.ll_back).setOnClickListener(this);
        findViewById(R.id.btn_back).setOnClickListener(this);
        llLayer.setEmptyViewRetryClickListener(this);
        llLayer.setErrorViewRetryClickListener(this);
    }
}